package com.luban.springmybatis;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;

import java.util.Set;

public class MyMapperScanner extends ClassPathBeanDefinitionScanner {
    public MyMapperScanner(BeanDefinitionRegistry registry) {
        super(registry);
    }

    /**
     * 是接口，才是候选的beanDefinition
     *
     * @param beanDefinition beanDefinition
     * @return boolean
     */
    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
        return beanDefinition.getMetadata().isInterface();
    }

    /**
     * 根据包路径扫描
     *
     * @param basePackages basePackages
     * @return Set<BeanDefinitionHolder>
     */
    @Override
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages);
        for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) {
            GenericBeanDefinition beanDefinition = (GenericBeanDefinition) beanDefinitionHolder.getBeanDefinition();
            //设置FactoryBean中getObject的Class类型
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(beanDefinition.getBeanClassName());
            //设置MapperFactoryBean~BeanClassName
            beanDefinition.setBeanClassName(MyMapperFactoryBean.class.getName());
            //AUTOWIRE_BY_TYPE
            beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
        }
        return beanDefinitionHolders;
    }

}
